// Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
package com.tencent.yolov5ncnn

import android.provider.Settings
import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.location.LocationManager
import android.net.ConnectivityManager
import android.net.ConnectivityManager.NetworkCallback
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.net.wifi.WifiManager
import android.net.wifi.WifiNetworkSpecifier
import android.os.Build
import android.os.Bundle
import android.os.PatternMatcher
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import java.io.File


// 确保导入正确的包
class MainActivity : Activity() {
    private var toIndex: Button? = null
    private var connectWifi: Button? = null

    /** Called when the activity is first created.  */
    @SuppressLint("ShowToast")
    @RequiresApi(Build.VERSION_CODES.Q)
    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main)
        ActivityCompat.requestPermissions(
            this,
            arrayOf(
                Manifest.permission.CAMERA,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_WIFI_STATE
            ),
            1
        )
        //打开定位
        if (!isLocationEnabled()) {
            val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
            startActivity(intent)
        }
//打开连接wifi
        val  wifiutils=WifiUtils(this)
//        wifiutils.openWifi()
        val configs=wifiutils.createWifiConfig("IPCAM-458839","01234567",3)
//        wifiutils.disconnectWifi()
        wifiutils.connectToWifi(configs)

        //创建文件夹
        MediaFileUtils.getOutputMediaFile(true)
        toIndex = findViewById<View>(R.id.toIndex) as Button

        // 设置按钮的点击事件监听器
        toIndex!!.setOnClickListener {
            // 创建一个 Intent 对象，指定要启动的目标 Activity
            val intent = Intent(this, index::class.java)
            // 在发送Activity中
            val name = one()
            intent.putExtra("wifiName", name)
            // 启动目标 Activity
            startActivity(intent)
        }

        //检查wifi名称
        val checkWifi = findViewById<View>(R.id.checkWifi) as Button
        checkWifi!!.setOnClickListener(View.OnClickListener {

            val name = one()
            Toast.makeText(this, "当前WiFi名称: $name", Toast.LENGTH_SHORT)
            Log.d("wifiname", name)
        })
        val toNetwork = findViewById<View>(R.id.toNetwork) as Button
        toNetwork!!.setOnClickListener(View.OnClickListener { // 创建一个 Intent 对象，指定要启动的目标 Activity
            val intent = Intent(this, network::class.java)

            // 启动目标 Activity
            startActivity(intent)
        })


        //创建csv
        val filePath = MediaFileUtils.getOutputMediaFile(true)?.parent// 替换为你要检查的文件路径
        val file = File(filePath + "/pic.csv")
        if (file.exists()) {
            println("File exists at $filePath")
        } else {
            file.bufferedWriter().use {
            }
        }
    }

    private fun isLocationEnabled(): Boolean {
        //检查定位是否打开
        val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
                locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
    }

    private fun one(): String {
        val wifiManager = (applicationContext.getSystemService(WIFI_SERVICE) as WifiManager)!!
        val wifiInfo = wifiManager!!.connectionInfo
        val SSID = wifiInfo.ssid

        return SSID.replace("\"", "")
    }

    companion object {
        private const val SELECT_IMAGE = 1
    }

    @RequiresApi(Build.VERSION_CODES.Q)
    private fun connectToWifi(pwd: String) {
        val ssid = "IPCAM-458839"
        val wifiNetworkSpecifier = WifiNetworkSpecifier.Builder()
//            .setSsid(ssid)
            .setSsidPattern(PatternMatcher("IPCAM", PatternMatcher.PATTERN_PREFIX))
            .setWpa2Passphrase(pwd)
            .build()

        val request = NetworkRequest.Builder()
            .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
            .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
            .setNetworkSpecifier(wifiNetworkSpecifier)
            .build()

        val connectivityManager =
            this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val networkCallback = object : NetworkCallback() {

        }
        connectivityManager.requestNetwork(request, networkCallback)
    }


}
